#!/usr/bin/perl -w
#   Written by Jimmy Saw - 10-11-2007
#   This program takes a Genbank file and extract rRNA and tRNA information 
#   You have to redirect output to a file
#   perl parse-gb2rna.pl x.gbk $molid > y.txt    

use Bio::SeqIO;

my $seqio_obj = Bio::SeqIO->new (-file => $ARGV[0], -format => 'genbank');
our $mol_id = $ARGV[1];
my $seq_obj = $seqio_obj->next_seq;

print "mol_id", "\t", "gene_id", "\t", "type", "\t", "gene_start", "\t", "gene_stop", "\t", "strand", "\t", "product", "\t", "gene_name","\n";

for my $feat_obj ($seq_obj->get_SeqFeatures){
    if ($feat_obj->primary_tag eq "rRNA"){
        if ($feat_obj->has_tag('locus_tag') && $feat_obj->has_tag('product')){
            for my $locus_tag ($feat_obj->get_tag_values('locus_tag')){
                my $start = $feat_obj->start;
                my $stop = $feat_obj->end;
                my $strand = $feat_obj->strand;
                my $product = $feat_obj->get_tag_values('product');
                my $outseq = $feat_obj->seq->seq();
                print $mol_id, "\t", $locus_tag,"\t", "rRNA", "\t", $start, "\t", $stop, "\t", $strand, "\t", $product, "\t", $outseq, "\n";
            }
        }

        elsif ($feat_obj->has_tag('product')){
            for my $product ($feat_obj->get_tag_values('product')){
              my $locus_tag = "No locus tag available"; 
              my $start = $feat_obj->start;
              my $stop = $feat_obj->end;
              my $strand = $feat_obj->strand;
              my $outseq = $feat_obj->seq->seq();
              print $mol_id, "\t", $locus_tag,"\t", "rRNA", "\t", $start, "\t", $stop, "\t", $strand, "\t", $product, "\t", $outseq, "\n";
            }
        }
    }
    
    if ($feat_obj->primary_tag eq "tRNA"){
        if ($feat_obj->has_tag('locus_tag') && $feat_obj->has_tag('product')){
            for my $locus_tag ($feat_obj->get_tag_values('locus_tag')){
                my $start = $feat_obj->start;
                my $stop = $feat_obj->end;
                my $strand = $feat_obj->strand;
                my $product = $feat_obj->get_tag_values('product');
                my $outseq = $feat_obj->seq->seq();
                print $mol_id, "\t", $locus_tag,"\t", "tRNA", "\t", $start, "\t", $stop, "\t", $strand, "\t", $product, "\t", $outseq, "\n";
            }
        }

        elsif ($feat_obj->has_tag('product')){
            for my $product ($feat_obj->get_tag_values('product')){
              my $locus_tag = "No locus tag available";
              my $start = $feat_obj->start;
              my $stop = $feat_obj->end;
              my $strand = $feat_obj->strand;
              my $outseq = $feat_obj->seq->seq();
              print $mol_id, "\t", $locus_tag,"\t", "tRNA", "\t", $start, "\t", $stop, "\t", $strand, "\t", $product, "\t", $outseq, "\n";
            }
        }
    }
}
